import { tenRequest } from '@/utils/request'
import { useUserStore } from '@/store'
import { useRelativeStore } from '@/store/modules/relative'
import { getToken } from '@/utils/auth'

// 1. 心跳检测接口
export function ping(channelName) {
  const userStore = useUserStore()
  const data = {
    request_id: userStore.requestId,
    channel_name: channelName || userStore.channelName
  }
  return tenRequest({
    url: '/agents/ping',
    method: 'post',
    data: data,
    headers: {
      isToken: false
    }
  })
}

// 2. 生成RTC Token接口
export function generateToken(channelName, uid) {
  const userStore = useUserStore()
  const data = {
    request_id: userStore.requestId,
    channel_name: channelName || userStore.channelName,
    uid: parseInt(uid || userStore.uid)
  }
  return tenRequest({
    url: '/token/generate',
    method: 'post',
    data: data,
    headers: {
      isToken: false
    }
  })
}

  // 3. 启动Worker接口
  export function startWorker(data) {
    return tenRequest({
      url: '/agents/start',
      method: 'post',
      data: data,
      headers: {
        isToken: false
      }
    })
  }

  // 4. 停止Worker接口
  export function stopWorker(channelName) {
    const userStore = useUserStore()
    const data = {
      request_id: userStore.requestId,
      channel_name: channelName || userStore.channelName
    }
    
    console.log('stopWorker called with data:', data)
    
    return tenRequest({
      url: '/agents/stop',
      method: 'post',
      data: data,
      headers: {
        isToken: false
      }
    })
  }

  /**
   * 便捷方法：启动Agent服务
   * @param {Object} params - 启动参数
   * @param {string} [params.channelName] - 频道名（可选，默认使用存储的值）
   * @param {string} params.graphName - 图名称
   * @param {string|number} [params.userUid] - 用户ID（可选，默认使用存储的值）
   * @param {string} [params.voice_type] - 声音类型
   * @returns {Promise} API响应
   */
  export function startAgent(params) {
    const userStore = useUserStore()
    const relativeStore = useRelativeStore()
    const {
      channelName = userStore.channelName,
      graphName,
      userUid = userStore.uid,
      voice_type,
      cluster,
      relativeId = relativeStore.currentRelativeId
    } = params
    
    // 参数验证
    if (!channelName || !graphName || !userUid) {
      return Promise.reject(new Error('graphName is required, and channelName and userUid must be provided or available in store'))
    }
    
    return startWorker({
      request_id: userStore.requestId,
      channel_name: channelName,
      graph_name: graphName,
      user_uid: parseInt(userUid),
      properties: {
        "tts": {
          "voice_type": voice_type,
          "cluster": cluster,
        },
        "llm": {
          "api_key": getToken(),
          "relative_id": relativeId,
          "user_id": userStore.id
        }
      }
    })
  }

/**
 * 便捷方法：停止Agent服务
 * @param {string} [channelName] - 频道名（可选，默认使用存储的值）
 * @returns {Promise} API响应
 */
export function stopAgent(channelName) {
  const userStore = useUserStore()
  console.log('stopAgent called with channelName:', channelName)
  console.log('userStore.channelName:', userStore.channelName)
  
  if (!channelName && !userStore.channelName) {
    return Promise.reject(new Error('channelName is required either as parameter or in store'))
  }
  
  return stopWorker(channelName || userStore.channelName)
}

/**
 * 便捷方法：获取RTC Token
 * @param {string} [channelName] - 频道名（可选，默认使用存储的值）
 * @param {string|number} [uid] - 用户ID（可选，默认使用存储的值）
 * @returns {Promise} API响应
 */
export function getRTCToken(channelName, uid) {
  const userStore = useUserStore()
  if ((!channelName && !userStore.channelName) || (!uid && !userStore.uid)) {
    return Promise.reject(new Error('channelName and uid are required either as parameters or in store'))
  }
  
  return generateToken(channelName || userStore.channelName, uid || userStore.uid)
}





